#!/bin/bash

# 设置颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 获取版本号
VERSION=${1:-$(date +%Y%m%d_%H%M%S)}

echo -e "${GREEN}=== LikeAdmin Python 生产环境镜像构建脚本 ===${NC}"
echo -e "${BLUE}版本号: ${VERSION}${NC}"

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo -e "${RED}错误: Docker 未安装${NC}"
    exit 1
fi

# 提示配置Docker镜像源
echo -e "${YELLOW}提示: 为加快下载速度，建议配置Docker镜像源${NC}"
echo -e "${BLUE}配置文件位置:${NC}"
echo -e "  Linux: /etc/docker/daemon.json"
echo -e "  Windows: %programdata%\\docker\\config\\daemon.json"
echo -e "  macOS: ~/.docker/daemon.json"
echo -e "${BLUE}参考配置:${NC}"
echo -e "  cp daemon.json /etc/docker/daemon.json"
echo -e "  systemctl restart docker"
echo ""

# 设置镜像标签
FASTAPI_IMAGE="likeadmin-python:fastapi-${VERSION}"
ADMIN_IMAGE="likeadmin-python:admin-${VERSION}"
NGINX_IMAGE="likeadmin-python:nginx-${VERSION}"

# 构建FastAPI镜像
echo -e "${YELLOW}构建 FastAPI 镜像...${NC}"
cd ../server
docker build -f ../docker-prod/Dockerfile.fastapi -t ${FASTAPI_IMAGE} .
if [ $? -ne 0 ]; then
    echo -e "${RED}FastAPI 镜像构建失败${NC}"
    exit 1
fi
echo -e "${GREEN}FastAPI 镜像构建成功: ${FASTAPI_IMAGE}${NC}"

# 构建Admin UI镜像
echo -e "${YELLOW}构建 Admin UI 镜像...${NC}"
cd ../admin
docker build -f ../docker-prod/Dockerfile.admin -t ${ADMIN_IMAGE} .
if [ $? -ne 0 ]; then
    echo -e "${RED}Admin UI 镜像构建失败${NC}"
    exit 1
fi
echo -e "${GREEN}Admin UI 镜像构建成功: ${ADMIN_IMAGE}${NC}"

# 构建Nginx镜像
echo -e "${YELLOW}构建 Nginx 镜像...${NC}"
cd ../docker-prod
docker build -f Dockerfile.nginx -t ${NGINX_IMAGE} .
if [ $? -ne 0 ]; then
    echo -e "${RED}Nginx 镜像构建失败${NC}"
    exit 1
fi
echo -e "${GREEN}Nginx 镜像构建成功: ${NGINX_IMAGE}${NC}"

# 显示构建结果
echo -e "${GREEN}=== 镜像构建完成 ===${NC}"
echo -e "${BLUE}FastAPI 镜像: ${FASTAPI_IMAGE}${NC}"
echo -e "${BLUE}Admin UI 镜像: ${ADMIN_IMAGE}${NC}"
echo -e "${BLUE}Nginx 镜像: ${NGINX_IMAGE}${NC}"

# 保存镜像到文件
echo -e "${YELLOW}保存镜像到文件...${NC}"
docker save ${FASTAPI_IMAGE} ${ADMIN_IMAGE} ${NGINX_IMAGE} -o likeadmin-python-${VERSION}.tar
if [ $? -eq 0 ]; then
    echo -e "${GREEN}镜像已保存到: likeadmin-python-${VERSION}.tar${NC}"
else
    echo -e "${RED}镜像保存失败${NC}"
fi

# 显示镜像大小
echo -e "${YELLOW}镜像大小信息:${NC}"
docker images | grep likeadmin-python

echo -e "${GREEN}=== 构建完成 ===${NC}"
echo -e "${YELLOW}部署命令:${NC}"
echo -e "${BLUE}VERSION=${VERSION} docker-compose up -d${NC}" 